package com.jp.knowledge.fragment;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapRegionDecoder;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;

import com.bm.library.PhotoView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.Request;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SizeReadyCallback;
import com.bumptech.glide.request.target.Target;
import com.bumptech.glide.request.target.ViewTarget;
import com.facebook.imageutils.BitmapUtil;
import com.jiayen.util.ToasUtil;
import com.jp.knowledge.R;
import com.jp.knowledge.activity.BaseFragment;
import com.jp.knowledge.logic.DownloadLogic;
import com.jp.knowledge.util.BtimapUtil;
import com.jp.knowledge.util.L;
import com.jp.knowledge.util.SignVerifyUtil;
import com.jp.knowledge.util.TimeUtil;

import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import rx.Observable;
import rx.Observer;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

/**
 * @author jiayen     2017-06-09 14:50:48
 * 图片显示fragment
 */
public class ImageFragment extends BaseFragment {

    private View mView;

    @ViewInject(R.id.imge)
    private PhotoView photoView;

    @ViewInject(R.id.progress)
    private ProgressBar  progressBar;

    private   String url;

    private  Bitmap bitmap;
    private Handler handler = new Handler();

    private DownloadLogic downloadLogic;
    public ImageFragment(){

    }
    public    ImageFragment  newInstance(String img){
        this.url=img;
        return this;
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        mView = inflater.inflate(R.layout.fragment_image, container, false);
        x.view().inject(this,mView);

        init();
        return mView;
    }

    @Override
    protected void onlazyLoad() {
        super.onlazyLoad();

        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
//                Glide.with(mContext)
//                        .load(url)//列表缩略图
//                        .asBitmap()
//                        .diskCacheStrategy(DiskCacheStrategy.SOURCE)
//                        .into(new ViewTarget<View, Bitmap>(photoView){
//                            @Override
//                            public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
//                                if(resource!=null&&!resource.isRecycled()) {
//                                    bitmap = resource;
//                                    progressBar.setVisibility(View.GONE);
//                                    photoView.setImageBitmap(bitmap);
//                                }
//                            }
//                        });
//                setBitmap();
            }
        },200);
    }

    private void init(){
        downloadLogic = new DownloadLogic(mContext,false);
        downloadLogic.setDownloadCallback(new DownloadLogic.DownloadCallback() {
            @Override
            public void success(String path) {
                    setBitmap(path);
            }
        });
        photoView.enable();
        progressBar.setVisibility(View.VISIBLE);
        String path =  mContext.getCacheDir().getPath()+"/img_cache/"+ SignVerifyUtil.encrypt(url)+".jpg";
        File file = new File(path);
        if(file.exists()){
            setBitmap(path);
        }else {
            downloadLogic.download(url,path);
        }

    }

    /***
     * 设置图片
     * @param path
     */
    private void setBitmap(final String path) {

        Observable.create(new Observable.OnSubscribe<Object>() {
            @Override
            public void call(Subscriber<? super Object> subscriber) {
                handBitmap(path);
                subscriber.onNext(path);
            }
        }).subscribeOn(Schedulers.io())
          .observeOn(AndroidSchedulers.mainThread())
          .subscribe(new Observer<Object>() {
              @Override
              public void onCompleted() {

              }
              @Override
              public void onError(Throwable e) {
                  ToasUtil.toast(mContext,"加载图片失败");
              }
              @Override
              public void onNext(Object o) {
                    if(bitmap!=null&&!bitmap.isRecycled()){
                        progressBar.setVisibility(View.GONE);
                        photoView.setImageBitmap(bitmap);
                    }else{
                        ToasUtil.toast(mContext,"加载图片失败");
                    }
              }
          });

    }
    private  void    handBitmap(String path){
       bitmap =  BtimapUtil.decodeSampledBitmapFromFile(path,screenWidth,screenHeight);
//        //创建bitmap工厂的配置参数
//        BitmapFactory.Options options = new BitmapFactory.Options();
//        //返回一个null 没有bitmap   不去真正解析位图 但是能返回图片的一些信息(宽和高)
//        options.inJustDecodeBounds = true;
//        BitmapFactory.decodeFile(path,options);
//        //[3]获取图片的宽和高
//        int imgWidth = options.outWidth;
//        int imgHeight = options.outHeight;
//        //[4]计算缩放比
//        int scale = 1;  //我们定义的缩放比
//        int scalex =  imgWidth/screenWidth;
//        int scaley = imgHeight /screenHeight;
//        if (scalex >=scaley&&scalex > scale) {
//            scale = scalex;
//        }
//        if (scaley > scalex && scaley>scale) {
//            scale = scaley;
//        }
//       L.e("缩放比为:"+scale);
//
//        //[5]按照缩放比显示图片
//        options.inSampleSize = scale;
//
//        //[6]开始真正的解析位图
//        options.inJustDecodeBounds = false;
//        try {
//            bitmap = BitmapFactory.decodeFile(path,options);
//        }catch (Exception e){
//            L.e(e.getMessage());
//        }

    }




    @Override
    public void onDestroyView() {
        super.onDestroyView();
//        Glide.clear(photoView);
//        photoView.setImageBitmap(null);
        if(bitmap!=null) {
            photoView.setImageBitmap(null);
            bitmap.recycle();
            bitmap = null;
            System.gc();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if(bitmap!=null) {
            bitmap.recycle();
            bitmap = null;
            System.gc();
        }
    }

}
